//
//  HomeViewController.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/16/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "HomeViewController.h"
#import "QRCodesManager.h"
#import "WiFiViewController.h"
#import "LocationViewController.h"
#import "OtherViewController.h"
#import "ContactViewController.h"
#import "WebViewController.h"
#import "EventViewController.h"
#import "QRUrl.h"


@interface HomeViewController ()

@end

@implementation HomeViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    _groupedQrCodes = [[QRCodesManager sharedInstance] groupedQrCodes];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - User Interaction

// Camera Button Tapped
- (IBAction)cameraButtonTapped:(id)sender {
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    reader.supportedOrientationsMask = ZBarOrientationMask(UIInterfaceOrientationPortrait);
    
    ZBarImageScanner *scanner = reader.scanner;
    
    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25 config: ZBAR_CFG_ENABLE to: 0];
    
    // present and release the controller
    [self presentModalViewController:reader animated:YES];
    
    [_tableView reloadData];
}


#pragma mark - ZBarReaderDelegate Methods

- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    [reader dismissModalViewControllerAnimated: YES];
    
    // ADD: get the decode results
    id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;
    
    NSLog(@"%@", symbol.data);
    _qrData = symbol.data;
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"qr_code_alert_title", nil) message:NSLocalizedString(@"qr_code_alert_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"alert_cancel", nil) otherButtonTitles:NSLocalizedString(@"alert_done", nil), nil];
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alertView show];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[[QRCodesManager sharedInstance] sortedKeys] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *category = [[[QRCodesManager sharedInstance] sortedKeys] objectAtIndex:section];
    return [[_groupedQrCodes objectForKey:category] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qrCodeCell"];
    
    NSString *category = [[[QRCodesManager sharedInstance] sortedKeys] objectAtIndex:indexPath.section];
    QRCode *code = [[_groupedQrCodes objectForKey:category] objectAtIndex:indexPath.row];
    
    cell.textLabel.text = code.name;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[[QRCodesManager sharedInstance] sortedKeys] objectAtIndex:section];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *category = [[[QRCodesManager sharedInstance] sortedKeys] objectAtIndex:indexPath.section];
    _qrCode = [[_groupedQrCodes objectForKey:category] objectAtIndex:indexPath.row];
    
    switch (_qrCode.qrType) {
        case QRWiFiType : {
            [self performSegueWithIdentifier:@"Home_To_WifiScreen" sender:self];
            break;
        }
        case QRContactType : {
            [self performSegueWithIdentifier:@"Home_ContactScreen" sender:self];
            break;
        }
        case QREventType : {
            [self performSegueWithIdentifier:@"Home_EventScreen" sender:self];
            break;
        }
        case QRLocationType : {
            [self performSegueWithIdentifier:@"Home_LocationScreen" sender:self];
            break;
        }
        case QRURLType : {
            [self performSegueWithIdentifier:@"Home_WebView" sender:self];
            break;
        }
        case QROtherType : {
            [self performSegueWithIdentifier:@"Home_OtherScreen" sender:self];
            break;
        }
        default:
            break;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
        NSString *category = [[[QRCodesManager sharedInstance] sortedKeys] objectAtIndex:indexPath.section];
        QRCode *code = [[_groupedQrCodes objectForKey:category] objectAtIndex:indexPath.row];
        
        [[QRCodesManager sharedInstance] deleteQrCode:code];
        if ([[_groupedQrCodes objectForKey:category] count] == 0) {
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
        } else {
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
}

#pragma mark - UIAlertViewDelegate Methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        UITextField *nameTextField = [alertView textFieldAtIndex:0];
        QRCode *qrCode = [[QRCodesManager sharedInstance] qrCodeFromString:_qrData withName:nameTextField.text];
        NSIndexPath *indexPath = [[QRCodesManager sharedInstance] indexPathOfQrCode:qrCode];
        if (indexPath.row > 0) {
            [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
        } else {
            [_tableView insertSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
    UITextField *nameTextField = [alertView textFieldAtIndex:0];
    if (nameTextField.text.length > 0) {
        return YES;
    }
    return NO;
}

- (void)viewDidUnload {
    _tableView = nil;
    [super viewDidUnload];
}

#pragma mark - Seuque Delegate

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"Home_To_WifiScreen"]) {
        WiFiViewController *wifiViewController = (WiFiViewController *)[segue destinationViewController];
        wifiViewController.qrWifi = (QRWiFi *)_qrCode;
    } else if ([[segue identifier] isEqualToString:@"Home_LocationScreen"]) {
        LocationViewController *locationViewController = (LocationViewController *)[segue destinationViewController];
        locationViewController.qrLocation = (QRLocation *)_qrCode;
    } else if([[segue identifier] isEqualToString:@"Home_ContactScreen"]) {
        ContactViewController *contactViewController = (ContactViewController *) [segue destinationViewController];
        contactViewController.qrContact = (QRContact *)_qrCode;
    } else if ([[segue identifier] isEqualToString:@"Home_WebView"]) {
        WebViewController *webViewController = (WebViewController *) [segue destinationViewController];
        QRUrl *qrUrl = (QRUrl *)_qrCode;
        webViewController.url = qrUrl.url;
    } else if ([[segue identifier] isEqualToString:@"Home_EventScreen"]) {
        EventViewController *eventViewController = (EventViewController *)[segue destinationViewController];
        eventViewController.qrEvent = (QREvent *)_qrCode;
    }
    else {
        OtherViewController *otherViewController = (OtherViewController *)[segue destinationViewController];
        otherViewController.qrCode = _qrCode;
    }
}
@end
